import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import result.Result;
import tasks.Task;

public class ImageProcessingTask extends Task {

	private static final int DIM = 10;
	private byte[] image;

	public ImageProcessingTask(int id, byte[] image) {
		super(id);
		this.image = image;
	}

	@Override
	public void run() {
		try {
			ImageIcon im =  new ImageIcon(image);
			Image source = im.getImage();
			int w = source.getWidth(null);
			int h = source.getHeight(null);
			BufferedImage sourceImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
			Graphics2D g2d = (Graphics2D)sourceImage.getGraphics();
			g2d.drawImage(source, 0, 0, null);
			g2d.dispose();

			
			float[] matrix = new float[DIM * DIM];
			for (int i = 0; i < DIM * DIM; i++)
				matrix[i] = 1.0f/(DIM * DIM);
			BufferedImage blurredImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB );

			BufferedImageOp op = new ConvolveOp( new Kernel(DIM, DIM, matrix), ConvolveOp.EDGE_NO_OP, null );
			op.filter(sourceImage, blurredImage);

//			JFrame j=new JFrame2(blurredImage);
//			j.setSize(1000,1000);
//			j.setVisible(true);


			ByteArrayOutputStream stream = new ByteArrayOutputStream(200000); 
			ImageIO.write(blurredImage,
					"jpg",
					stream);
			stream.flush();
			stream.close();
			image = stream.toByteArray();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public Result getResult() {
		return new ImageProcessingResult(id,image);
	}

	@Override
	public void cancel() {
		// TODO Auto-generated method stub

	}

}
